package com.hengshan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hengshan.domain.entity.User;
import com.hengshan.domain.LoginUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserServiceImpl userService;
    private final MenuServiceImpl menuService;

    /**
     * 重写UserDetailsService接口中的loadUserByUsername，从数据库中加载用户
     *
     * @param username 用户名
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username).eq(User::getStatus, UserServiceImpl.USER_STATUS_ON);
        User user = userService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new RuntimeException("用户不存在");
        } else if ("0".equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new RuntimeException("用户已被停用");
        }
        // 查询用户权限信息
        List<String> permissions = menuService.selectPermsByUser(user);
        return new LoginUser(user, permissions);
    }
}
